<template>
  <div class="defectOrder flowCloumn h100">
    <div class="constentmain h100">
      <div class="tableContent">
        <listTableNew v-bind="tableSetting" ref="klTable"></listTableNew>
      </div>
      <div class="annotations list-table-main">
        注：
        <span class="circle normal-bg"></span>
        按期的工单
        <span class="circle remind-bg"></span>
        即将到期的工单
        <span class="circle warning-bg"></span>
        已超期的工单
        <span class="circle gray-bg"></span>
        已废弃工单
      </div>
    </div>
    <dialogPublic
      :title="'作废理由'"
      :show.sync="showDialog"
      appendTobody
      @doClose="closeInvalidReason"
      @doSubmit="toInvalid"
      class="invalidReason"
    >
      <el-input
        v-if="showDialog"
        type="textarea"
        :rows="6"
        placeholder="请输入内容"
        v-model="inputReason"
      ></el-input>
    </dialogPublic>
  </div>
</template>
<script>
import {
  getListApi, //列表
  deleteListApi, //删除
  adeprecateApi, //作废
} from "@/api/orderManagement/defectOrder";
export default {
  components: {},
  props: {
    //设备台账当前设备
    currentNode: {
      type: Object,
      default: () => {
        return {};
      },
    },
    menuType: {
      type: String,
      default: "",
    },
    showType: {
      type: String,
      default: "",
    },
    isEquipment:{
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      pageType: "list",
      isFirstQuery: true,
      showDialog: false,
      invalidReason: "",
      inputReason: "",
      formData: {},
      urlQuery: null,
      currentDevice: {},
      tableSetting: {
        defaultQueryFirst: true,
        selectionShow: true,
        selectableMethod: (row, index) => {
          return ["WAIT_DISPATCH", "WAIT_EXECUTE", "IN_EXECUTE"].includes(
            row.status
          );
        },
        showCustomBtn: true,
        showFilterBtn: true,
        pageConfig: {
          pageCode: "defectOrder-" + this.menuType, //页面标识，用来存储过滤器以及自定义列的时候用
          userId: this.$store.getters.userInfo.id,
        },
        searchObj: {
          searchMethod: (params, sortStr) => {
            if(typeof params.collectionSearch !== 'boolean') {
              this.$message.warning('向上归集筛选条件不能为空！')
              return
            }
            this.getTableData(params, sortStr);
          },
          queryData: {
            page: 1,
            pageSize: 15,
            type: "",
            collectionSearch: false,
          },
          searchArr: [
            {
              type: "input",
              label: "标题",
              model: "title",
            },
            {
              type: "dept",
              label: "设备管理单位",
              model: "deptManageName",
              idsStr: "deptManage",
              clearable: true,
            },

            {
              type: "device",
              label: "设备",
              model: "equipmentName",
              idsStr: "equipmentId",
            },
            {
              type: "input",
              label: "缺陷关键字",
              model: "keys",
            },
            {
              label: "状态",
              model: "statusList",
              type: "select",
              multiple: true,
              option: this.$store.getters["dirtData"]("order_defect_status"),
            },
            {
              type: "input",
              label: "工单编号",
              model: "code",
            },
            {
              label: "创建时间",
              model: "createTime",
              type: "datetimerange",
            },
            {
              type: "userOnly",
              label: "发现人",
              model: "finderName",
              idsStr: "finder",
              placeholder: "请输入",
            },
            {
              label: "所属类别",
              model: "type",
              type: "select",
              option: this.$store.getters["dirtData"]("order_defect_type"),
            },
            {
              label: "专业",
              model: "major",
              type: "select",
              // multiple: true,
              option: this.$store.getters["dirtData"]("common_major"),
            },
            {
              label: "应完成处理时间",
              model: "expectTime",
              type: "datetimerange",
            },
            {
              label: "工单来源",
              model: "source",
              type: "select",
              option: this.$store.getters["dirtData"]("order_defect_source")
            },
            {
              label: "缺陷等级",
              model: "level",
              type: "select",
              // multiple: true,
              option: this.$store.getters["dirtData"]("defect_order_level"),
            },
          ],
        },
        actionList: [
          {
            name: "新建",
            icon: "el-icon-plus",
            disabled: !this.$store.getters["isBtnAuth"]("add"),
            content: this.$store.getters["isBtnAuth"]("add")
              ? null
              : "未授权此功能！",
            method: (row) => {
              this.toAdd();
            },
          },
          {
            name: "作废",
            icon: "el-icon-delete",
            disabled: !this.$store.getters["isBtnAuth"]("invalid"),
            content: this.$store.getters["isBtnAuth"]("invalid")
              ? null
              : "未授权此功能！",
            method: (row) => {
              this.showDialog = true;
            },
          },
          {
            name: "导出",
            icon: "icon-daochu",
            disabled: !this.$store.getters.isBtnAuth("export"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (row) => {
              this.export();
            },
          },
        ],
        column: [
          {
            label: "状态",
            prop: "status",
            scopeType: "formate",
            method: (row) => {
              let dom = "";
              let statusName =
                this.$store.getters["fineDirtDataName"](
                  "order_defect_status",
                  row.status
                ) || row.status;
              let colorStatus = row.trafficLight;
              if (row.status == "DEPRECATED") {
                dom =
                  '<span class="gray" title="废弃工单">' +
                  statusName +
                  "</span>";
              } else {
                if (colorStatus == "Normal") {
                  //正常
                  dom =
                    '<span class="normal" title="按期的工单">' +
                    statusName +
                    "</span>";
                } else if (colorStatus == "Warn") {
                  //即将到期
                  dom =
                    '<span class="remind" title="即将到期的工单">' +
                    statusName +
                    "</span>";
                } else if (colorStatus == "OverTime") {
                  //超期
                  dom =
                    '<span class="warning" title="已超期工单">' +
                    statusName +
                    "</span>";
                }
              }
              return dom;
            },
            sortable: "custom",
            width: "100px",
          },
          {
            label: "编号",
            prop: "code",
            width: "170px",
            sortable: "custom",
          },
          {
            label: "标题",
            prop: "title",
            showTooltip: true,
            sortable: "custom",
            width: "320px",
            // formatter: row => {
            //   let title =
            //     row.title ||
            //     this.$store.getters.userInfo.orgName +
            //       "-" +
            //       row.equipmentName +
            //       "-" +
            //       row.keys;
            //   return title;
            // }
          },
          {
            label: "设备管理单位",
            id: "deptManage",
            prop: "deptManageName",
            sortable: "custom",
            showTooltip: true,
            minWidth: "160px",
          },
          {
            label: "设备",
            prop: "equipmentName",
            sortable: "custom",
            showTooltip: true,
            minWidth: "210px",
          },
          {
            label: "缺陷关键字",
            prop: "keys",
            sortable: "custom",
            minWidth: "160px",
            showTooltip: true,
          },
          {
            label: "专业",
            prop: "major",
            sortable: "custom",
            formatter: (row) => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                row.major
              );
            },
            minWidth: "80px",
          },
          {
            label: "缺陷等级",
            prop: "level",
            sortable: "custom",
            formatter: (row) => {
              return this.$store.getters["fineDirtDataName"](
                "defect_order_level",
                row.level
              );
            },
            minWidth: "110px",
          },
          {
            label: "应完成处理时间",
            prop: "expectEndTime",
            sortable: "custom",
            minWidth: "140px",
          },
          {
            label: "当前节点",
            prop: "currNodeName",
            sortable: "custom",
            minWidth: "170px",
          },
          {
            label: "当前处理人",
            prop: "currNodeUser",
            sortable: "custom",
            showTooltip: true,
            minWidth: "120px",
          },
          {
            label: "发现人",
            prop: "finderName",
            sortable: "custom",
            minWidth: "90px",
          },
          {
            label: "创建时间",
            prop: "createTime",
            sortable: "custom",
            minWidth: "140px",
          },
        ],
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (val) => {
            this.gotoDetails(val);
          },
        },
      },
      searchData: {},
    };
  },
  watch: {
    menuType(val) {
      this.init();
    },
    currentNode: {
      handler: function (newVal, oldVal) {
        this.currentDevice = Object.assign({}, newVal); 
        let queryData = Object.assign(this.tableSetting.searchObj.queryData, {
          equipmentId: newVal.id,
          //equipmentName: newVal.name,
          collectionSearch: true,
          floor:newVal.floor,
        });
        this.tableSetting.searchObj.queryData = {};
        this.tableSetting.searchObj.queryData = queryData;
        setTimeout(() => {
          if (oldVal) {
            //不是第一次
            this.updateData();
          }
        }, 0);
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {},
  created() {
    //  /* 初始化查询条件 */
    // let endDate = this.$utils.getCurrentDate('minutes');
    // let day = new Date() - 1000 * 60 * 60 * 24 * 7;
    // let startDate = this.$utils.TimeFormat(day, 3);
    // this.$set(this.tableSetting.searchObj.queryData, "createTime", [
    //   startDate,
    //   endDate
    // ]);
    // this.$set(
    //   this.tableSetting.searchObj.queryData,
    //   "deptManageList",
    //   this.userInfo.deptName
    // );
    if (this.isEquipment) {
      this.tableSetting.searchObj.searchArr.unshift({
        label: "向上归集",
        unclearable: true,
        model: "collectionSearch",
        type: "select",
        option: [
          { label: "是", value: true },
          { label: "否", value: false },
        ],
      });
      this.tableSetting.searchObj.searchArr.splice(3,1);
    }
    /* 添加监听事件 */
    window.addEventListener("storage", this.updateData);
  },
  beforeDestroy() {
    /* 删除监听事件 */
    window.removeEventListener("storage", this.updateData);
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let href = window.location.href;
      this.urlQuery = href.split("?")[1];
      if (this.urlQuery) {
        let arr = JSON.parse(
          JSON.stringify(this.tableSetting.searchObj.searchArr)
        );
        arr.map((i) => {
          i.disabled = true;
        });
        this.tableSetting.searchObj.searchArr = arr;
      }
      if (this.menuType == "others") {
        let itemArr = [];
        //深度拷贝数组对象(可拷贝函数)
        $.extend(true, itemArr, this.tableSetting.searchObj.searchArr);
        let arr = [];
        itemArr.map((i) => {
          if (
            ["title", "deptManageName", "keys", "statusList"].includes(i.model)
          ) {
            arr.push(i);
          }
        });
        this.tableSetting.searchObj.searchArr = arr;
      }
      this.pageType = "edit";
      if (this.showType == "query") {
        this.tableSetting.selectionShow = false;
        this.tableSetting.showCustomBtn = false;
        this.tableSetting.showFilterBtn = false;
        this.tableSetting.actionList = [];
        setTimeout(() => {
          this.updateData();
        }, 1000);
      } else {
        this.$refs.klTable.getTableConfig(); //需要显示过滤器以及自定义列时要提前调用,不需要过滤器时不调用
      }
    },
    updateData() {
      if (this.$refs.klTable) {
        this.$refs.klTable.searchData();
      }
    },
    getTableData(params, sortStr) {
      let form = { ...params };
      if (this.urlQuery) {
        let arr = this.urlQuery.split("&");
        arr.map((i) => {
          let name = i.split("=")[0];
          let value = i.split("=")[1];
          if (!["page", "pageSize"].includes(name)) {
            form[name] = value;
          }
        });
      }
      // form.type = this.menuType;
      if (sortStr) {
        form.orders = sortStr;
      }
      if (form.createTime) {
        form.createStartTime = form.createTime[0] || "";
        form.createEndTime = form.createTime[1] || "";
        delete form.createTime;
      }
      if (form.expectTime) {
        form.expectEndTimeStart = form.expectTime[0] || "";
        form.expectEndTimeEnd = form.expectTime[1] || "";
        delete form.expectTime;
      }
      this.searchData = form;
      if (!this.isEquipment) {
        form.collectionSearch = false;
        delete form.floor;
      }
      getListApi(form)
        .then((res) => {
          let data = res.data.list || [];
          let total = res.data.total || 0;
          this.$set(this.tableSetting, "tableData", data);
          this.$set(this.tableSetting, "totalNumber", total);
        })
        .catch((e) => {
          this.$set(this.tableSetting, "tableData", []);
          this.$set(this.tableSetting, "totalNumber", 0);
        });
    },
    //打开详情页
    gotoDetails(data) {
      if (data) {
        this.pageType = this.$store.getters["isBtnAuth"]("edit")
          ? "edit"
          : "detail";
      }
      let form = {
        pageType: this.pageType,
        menuType: this.menuType,
      };
      if (this.pageType != "add") {
        form.id = data.id;
        form.status = data.status;
      }
      let { href } = this.$router.resolve({
        path: "/orderManagement/defectOrder/details",
        query: form,
      });
      window.open(href, "_blank");
    },
    //新建
    toAdd() {
      this.pageType = "add";
      this.gotoDetails();
    },
    //作废
    toInvalid() {
      let data = this.$refs.klTable.getSelectData();
      let ids = [];
      data.map((i) => {
        ids.push(i.id);
      });
      this.invalidReason = this.inputReason;
      if (this.invalidReason) {
        this.closeInvalidReason();
        let form = {
          orderIds: ids.toString(),
        };
        adeprecateApi(form).then((res) => {
          ids.map((i) => {
            this.$utils.addOperateLog(
              i,
              "作废了工单,作废原因：" + this.invalidReason
            );
          });
          this.$message.success("操作成功");
          this.invalidReason = "";
          this.updateData();
        });
      } else {
        this.$message.warning("请填写作废理由！");
      }
    },
    closeInvalidReason() {
      this.inputReason = "";
      this.showDialog = false;
    },
    //删除
    deleteRow() {
      let checkRow = this.$refs.klTable.getSelectData() || [];
      if (checkRow.length == 0) {
        this.$message.warning("请先选择要删除的数据！");
      } else {
        let deleteList = [];
        let isDelete = true;
        for (let i = 0; i < checkRow.length; i++) {
          let { id, status } = checkRow[i];
          if (["DRAFT"].includes(status)) {
            deleteList.push(id);
          } else {
            isDelete = false;
            //只有是草稿状态的数据是可以删除的
            this.$message.warning("已提交的数据不能删除！");
            break;
          }
        }
        let form = {
          ids: deleteList.toString(),
        };
        if (isDelete) {
          this.$confirm(`是否确认删除`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              deleteListApi(form).then((res) => {
                this.$message.success("操作成功");
                this.updateData();
              });
            })
            .catch((e) => {});
        }
      }
    },
    //导出
    export() {
      let paramStr = "";
      let params = this.searchData;
      delete params.orders;
      for (const key in params) {
        if (Object.hasOwnProperty.call(params, key)) {
          if (params[key] && params[key] != "") {
            paramStr += `${key}=${params[key]}&`;
          }
        }
      }
      paramStr = paramStr.substring(0, paramStr.length - 1);
      let path = `eam-service-order/defect/export?${paramStr}`;
      let fileName = `缺陷工单`;
      this.$utils.downloadFile(null, fileName, path);
    },
  },
};
</script>
<style lang="less" scoped>
.constentmain {
  position: relative;
}
.tableContent {
  min-height: 500px;
  height: 100%;
}
.annotations {
  text-align: left;
  height: 20px;
  line-height: 20px;
  position: absolute;
  bottom: 5px;
}
.circle {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 10px;
}
.invalidReason {
  /deep/.el-dialog {
    width: 400px;
  }
  //
}
</style>